package com.example.freewood.smartsecurity_manager.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UdpService extends Service {
    private DatagramSocket socket;
    private Handler myHandler;
    private SocketServer socketServer;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        String msg=intent.getStringExtra("msg");
        new SocketServer().start();


        if (!msg.equals("")&&!msg.equals("null")){
            Log.e("mylog", "msg--" + msg);
            Message message=myHandler.obtainMessage(1,msg);
            myHandler.sendMessage(message);
        }



        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Log.e("mylog","----onCreate");
        socketServer=new SocketServer();
        socketServer.start();
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        System.out.println("---destroy");
        socket.close();
        super.onDestroy();
    }


    class SocketServer extends Thread{
        @Override
        public void run() {
            if(socket==null){
                try {
                    socket = new DatagramSocket(5566);
                    byte datas[]=new byte[1024];
                    DatagramPacket packets=new DatagramPacket(datas,datas.length);

                    while (true) {
                        Log.e("mylog","循环接收中");
                        socket.receive(packets);
                        String rs = new String(packets.getData(), packets.getOffset(), packets.getLength());
                        System.out.println("--" + rs);
//                        EventBus.getDefault().post(
//                                new FirstEvent(rs));

                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            Log.e("mylog", "运行了Thread");
            Looper.prepare();
            myHandler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    Log.e("mylog","运行了Handle");

                    try {


                        InetAddress address=InetAddress.getByName("202.115.82.20");
                        String str=msg.obj.toString();

                        if(!str.equals("null")){
                            Log.e("mylog", str);
                            byte data[]=str.getBytes();
                            DatagramPacket packet=new DatagramPacket(data,data.length,address,5566);
                            socket.send(packet);
                        }
                        byte datas[]=new byte[1024];
                        DatagramPacket packets=new DatagramPacket(datas,datas.length);

                        while (true) {
                            Log.e("mylog","循环接收");
                            socket.receive(packets);
                            String rs = new String(packets.getData(), packets.getOffset(), packets.getLength());
                            System.out.println("--" + rs);
//                            EventBus.getDefault().post(
//                                    new FirstEvent(rs));

                        }

                    } catch (SocketException e) {
                        e.printStackTrace();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            };

            Looper.loop();
        }
    }
}
